/**
 * Created by WebStorm.
 * User: nirongxu
 * Date: 2019-01-02
 * Description: 文件描述
 */
import axios from "axios"
import NProgress from "nprogress"
import { Message } from "element-ui"
import qs from "qs"
import router from "../router"
import store from "../vuex"

// Authorization

// axios默认配置
axios.defaults.timeout = 1000000 // 超时时间
axios.defaults.baseURL = process.env.API_HOST

// axios.interceptors.request.use(config=> {
//   // 在发送请求之前做些什么
//   config.headers = {
   
//     'Content-Type': 'multipart/form-data'
//    }
//   return config;
//   },
// )
axios.interceptors.request.use(
  request => {
    const token = sessionStorage.getItem("token_bkv")
    
    if (token) {
      request.headers.PatientAuthorization = token
    }
    return request
  },
  error => {
    return Promise.reject(error)
  }
)

const logout = () => {
  Message({
    message: "登陆过期,请您重新登录",
    type: "warning"
  })
  store.dispatch(
    "setToken",
    null
  )
  sessionStorage.removeItem("token_bkv")
  router.push({path: "/"})
}

// http response 拦截器
axios.interceptors.response.use(
  response => {
    console.log("response", response)
    NProgress.done()
    if (response.data.code === 401) {
      logout()
      return Promise.resolve()
    }
    if (response.data.code === 500) {
      return Promise.reject(response)
    }
    return Promise.resolve(response)
  },
  error => {
    if (error.response) {
      if (error.response.status === 404) {
        Message({
          message: "请求地址出错",
          type: "warning"
        })
      } else if (error.response.status === 403 || error.response.status === 401) {
        logout()
      }
    }

    return Promise.reject(error.response) // 返回接口返回的错误信息
  }
)

export function ajax (url, data = {}, type = "GET", isFormData = false) {
  return new Promise((resolve, reject) => {
    let promise
    if (type === "GET") {
      promise = axios.get(url, {
        params: data
      })
    } else if (type === "POST") {
      if (isFormData) {
        promise = axios.post(url, data)
      } else {
        promise = axios.post(url, qs.stringify(data))
      }
    } else if (type === "PUT") {
      promise = axios.put(url, data)
    }
    promise
      .then(response => {
        resolve(response.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

export default axios
